package de.pernpas.calendar.controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.pernpas.calendar.databean.DataBean;
import de.pernpas.calendar.service.EventService;

@SuppressWarnings("serial")
public class Controller extends HttpServlet {
	private final Logger log = Logger.getLogger(Controller.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String page = req.getParameter("page");
		String redirectParams = getRedirectParams(req);
		log.fine("Page: " + "/" + page + ".jsp" + redirectParams);
		loadDataBean(page, req, resp);
		resp.sendRedirect("/" + page + ".jsp" + redirectParams);
	}
	
	private void loadDataBean(String page, HttpServletRequest req, HttpServletResponse resp) {
		if(page.equals("detail")){
		DataBean dataBean = new DataBean();
		dataBean.setEvents(EventService.getEvents(
				Integer.parseInt(req.getParameter("day")), 
				Integer.parseInt(req.getParameter("month")), 
				Integer.parseInt(req.getParameter("year")))); 
		}
	}

	@SuppressWarnings("unchecked")
	private String getRedirectParams(HttpServletRequest req) {
		String redirectParams = "?";
		Enumeration<String> params = req.getParameterNames();
		while(params.hasMoreElements()){
			String p = params.nextElement();
			if (!p.equalsIgnoreCase("page")) {
				if (!redirectParams.endsWith("?")) {
					redirectParams = redirectParams + "&";
				}
				redirectParams = redirectParams + p + "=" + req.getParameter(p);
				log.info("Parameter: " + p);
			}
		}
		return redirectParams;
	}
}
